const router = require("express-promise-router")();
const config = require('../config/config');
const moment=require('moment');
const GoodService=require('../services/goods');
const kindService=require('../services/kind');
const CabinetService=require('../services/cabinet');
router.post('/device_grid',async function (req,res){
    const {cabinetId,deviceId}=req.body;
    console.log(cabinetId,deviceId);
    const device=await GoodService.getGoodByBarcode(deviceId);
    console.log("cabinetId,deviceId",cabinetId,deviceId);
    if(!device){
        return res.send({error:'设备码错误'});
    }
    const kind=await kindService.getKindById(device.kindId);
    device.name=kind.name;
    device.category=kind.category;
    console.log(cabinetId)
    const grid=await CabinetService.getEmptyGrid(cabinetId);
    console.log("grid",grid);
    if(!grid){
        return res.send({error:'没有空格子'});
    }
    res.send({grid:grid.number,device});
});

router.post('/check_grid',async function (req,res){
    const {cabinetId,grid}=req.body;
    const result=await CabinetService.checkGrid(cabinetId,grid);
    if(result){
        return res.send({error:'柜门未关闭'});
    }
    res.send({success:true});
});

router.post('/save_device',async function (req,res){
    const {cabinetId,grid,device}=req.body;
    await CabinetService.saveDevice(cabinetId,grid,device);
    res.send({success:true});
});
router.post('/get_good',async function (req,res){
    const {cabinetId,listId}=req.body;
    const borrowList=await kindService.getBorrowListById(listId);
    if(!borrowList){
        return res.send({error:'领取码无效'});
    }
    const listInfo=borrowList.list[0]||{}
    const kind=listInfo.kind;
    const grid=await CabinetService.getDeviceGrid(cabinetId,kind.objectId);
    const barcode=grid.barcode;
    const good=await GoodService.getGoodByBarcode(barcode);
    //清除柜子的存储信息
    await CabinetService.clearDeviceGrid(grid.objectId);
    //修改borrowList的状态`
    kind.status='used'
    await kindService.changeListStatus(listId,[kind]);
    //修改物品的持有人
    await GoodService.setGoodOwner(grid.barcode,borrowList.user);
    //修改库存数量
    await GoodService.change_owner_count([{...kind,count:1}], borrowList.user,'sub');
    await kindService.change_used_count(borrowList,'add');
    //存储物品的领取记录
    await kindService.save_record(kind.objectId,good.objectId,borrowList.user,1,false);
    res.send({grid:grid.number,cid:grid.cid,device:{...good,name:kind.name,category:kind.category}});
});


router.post('/get_supplies', async function (req, res) {
    try {
        const { cabinetId, listId } = req.body;
        const borrowList = await kindService.getBorrowListById(listId);
        if (!borrowList) {
            res.send({ success: false, message: '领取码无效'});
        }
        if (borrowList.hasUsed) {
            res.send({ success: false,message: '已经领取过该物品' });
        }
        const listInfo = borrowList.list[0] || {};
        const kind = listInfo.kind;
        // 查询当前物品所有存在的位置
        const grid = await CabinetService.getSuppliesGrid(kind.objectId);
        // 过滤掉 cabinetId 不等于传入的 cabinetId 的数据
        const gridNow = grid.filter(item => item.cabinetId === cabinetId);
        // 根据需求数量选择网格
        let requiredCount = listInfo.count;
        let selectedGrids = [];
        let currentTotal = 0;

        for (const item of gridNow) {
            const quantityToTake = Math.min(item.count, requiredCount - currentTotal);
            currentTotal += quantityToTake;
            selectedGrids.push({ ...item, quantityToTake });
            if (currentTotal >= requiredCount) {
                break;
            }
        }
        console.log("item",requiredCount,currentTotal);
        console.log("selectedGrids",selectedGrids);
        // 检查是否满足需求数量
        if (currentTotal < requiredCount) {
            console.log("到这了1");
              // 满足需求时的处理逻辑
              const remainingCount = requiredCount - currentTotal;
              // 调整当前柜子的网格数量
              for (const item of selectedGrids) {
                  await CabinetService.clearSuppliesGrid(item.objectId, item.quantityToTake);
              }
              listInfo.count = remainingCount;
              await kindService.changeListStatus(listId, [kind]);
            //   await kindService.change_used_count(borrowList, 'add');
              const otherGrid = grid.filter(item => item.cabinetId != cabinetId);
              return res.send({
                  error: '当前柜子库存不足',
                  message: '请先在当前柜子领取后，再前往其他柜子继续领取。',
                  currentCabinetGrids: selectedGrids,
                  remainingCount: remainingCount,
                  otherGrids: otherGrid
              });
        } else {
            for (const item of selectedGrids) {
                await CabinetService.clearSuppliesGrid(item.objectId, item.quantityToTake);
            }
              borrowList.list[0].kind.status = 'used'; // 设置状态为 'used'
              await kindService.changeListStatus(listId,borrowList.list); // 使用整个更新后的 borrowList
            // await kindService.change_used_count(borrowList, 'add');
            res.send({ success: true, message: '物品领取成功', grids: selectedGrids });
        }

    } catch (error) {
        res.status(500).send({ error: error.message });
    }
});





module.exports = router;
